package tests;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import client.AppWindow;

import server.Server;

public class ServerAndClientStarter {

	private static ArrayList<Thread> threads = new ArrayList<Thread>();
	
	
	public static void main(String[] args) {
		new ServerAndClientStarter();
	}
	
	public ServerAndClientStarter() {
		startServer();
		
		try {Thread.sleep(3050L);} 
		catch (InterruptedException e) {e.printStackTrace();}
		  
		startClients(3);
	}
	
	private static int num = 0;
	public class ClientThread extends Thread
	{
		public AppWindow client;
		
		public ClientThread(String string) {
			super(string);
		}

		@Override
		public void run() {
			String localPath = "C:\\Users\\jessmatt\\Documents\\JHU\\605.401-FoundationsOfSWEng\\workspace\\ClueLess_\\";
			System.out.println("Starting GUI for: \t" + Thread.currentThread().getName());
			ProcessBuilder builder = new ProcessBuilder("java", "-cp", 
					localPath+"lib/*;"+localPath+"bin\\",
	                  "client.AppWindow"
					);
			
            Map<String, String> environment = builder.environment();

            environment.put("user.dir", 
            		localPath+"bin\\");
            try {
            	builder.redirectErrorStream(true);
            	builder.redirectOutput(new File(
            			localPath+"bin\\"+
            			(num ++)+
            			"out.txt")
            	);
				builder.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void startClients(int number) {
		for (int i = 0; i < number; i++)
		{
			System.out.print("Starting Client "+i+"...");
			Thread c = new ClientThread("client_"+i);
			c.start();
			threads.add(c);
			System.out.println("....completed starting Client "+i);
		}
	}

	private void startServer() {
		System.out.print("Starting Server ...");
		Thread server = new Thread() {
			public void run() {
				new Server();
			};
		};
		server.start();
		System.out.println("....completed");
		threads.add(server);
	}
}
